package com.jahentao.testcase;


import java.io.*;
import java.util.Map;

/**
 * 实现输入输出接口<br>
 * 输入输出格式在该事项类中，使用字符串格式
 * @author jahentao
 * @version 1.0
 * @updated 26-5月-2017 18:02:46
 */
public class ConcreteInputOutputFormat implements InputOutputFormat {

	public ConcreteInputOutputFormat(){

	}

	@Override
	public TestCase read(File infile) throws Exception {
		TestCase testCase = new TestCase();
	    testCase.setTestCaseInFile(infile);

		FileInputStream fileInputStream = new FileInputStream(infile);
        BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));

        Map<String, Object> map = testCase.getInMap();

		StringBuffer buffer = new StringBuffer();
		String line;
		while((line = br.readLine())!=null) {
            buffer.append(line+" ");
        }
        map.put("inputData", buffer.toString());

        fileInputStream.close();

        return testCase;
    }

	@Override
	public void writeTo(TestCase testCase) throws Exception {
        // 获取运行时环境，进行编译
        // 调用命令行接口
        Process pr = null;
        BufferedReader in = null;
        DataOutputStream os = null;
        StringBuffer command = new StringBuffer("F:\\tmp\\PAT\\pat1004.exe");
        try {
            // 操作底层操作系统的接口
            pr = Runtime.getRuntime().exec(command.toString());
            // 输入参数
            os = new DataOutputStream(
                    pr.getOutputStream());
            os.writeBytes((String) testCase.getInMap().get("inputData"));
            os.flush(); // 同时要将数据刷进去

            // 获得命令行输出
            in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String line;
            StringBuffer outputData = new StringBuffer();
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                outputData.append(line);
            }
            testCase.getOutMap().put("outputData",outputData.toString());
            /*int exitCode = */pr.waitFor();// 等待返回值 不为0是非正常
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
}